/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author banhbaochay
 */
public class Browser {

    public Browser() {
        desktopSupported = false;
        browseSupported = false;
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
            desktopSupported = true;
            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                browseSupported = true;
            }// end if desktop.isSupported(Desktop.Action.BROWSE)
        }// end if isDesktopSupported
        
    }// end constructor
    
    /**
     * 
     * @param url
     * @throws IOException 
     */
    public void browseURL(String url) throws IOException {
        if (isBrowseSupported()) {
            desktop.browse(URI.create(url));
        } else {
            
            String browserPath = getBrowsePathLinux();
            if (browserPath.equals("nobrowser")) {
                throw new UnsupportedOperationException();
            }// end if browserPath.equals("nobrowser")
            Runtime.getRuntime().exec(new String[]{browserPath, url});
            
        }// end if isSupported BROWSE
    }// end browseURL method
    
    /**
     * Get browser you have in your OS. Only use in Linux
     * @return full path to browser. Example: /usr/bin/firefox
     */
    private String getBrowsePathLinux() {
        String cmd = null;
        String[] browsers = {"firefox", "google-chrome", "opera", "epiphany",
            "konqueror", "conkeror", "midori", "kazehakase"};
        for (String browse : browsers) {
            try {
                Process p = Runtime.getRuntime().exec(new String[]{"which", browse});
                Thread.sleep(20);
                if (p.exitValue() == 0) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    cmd = in.readLine();
                    break;
                }
            } catch (Exception ex) {
                continue;
            }
        }
        return (cmd != null) ? cmd : "nobrowser";
    }
    
    private boolean desktopSupported;
    private boolean browseSupported;
    private Desktop desktop;

    /**
     * @return the desktopSupported
     */
    public boolean isDesktopSupported() {
        return desktopSupported;
    }

    /**
     * @return the browseSupported
     */
    public boolean isBrowseSupported() {
        return desktopSupported && browseSupported;
    }
}// end Browser class

